import { ref, reactive } from 'vue';

export const useBookList = ({
  queryList,
  formTypeList,
  searchParams,
  dataField = { field: 'records' },
}) => {
  const queryFormState = {
    pageNum: 1,
    pageSize: 100000,
  };
  // 查询表单form
  const queryParams = reactive({ ...queryFormState });

  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);
  // 查询数据
  async function queryData(searchParams = {}) {
    tableLoading.value = true;
    try {
      console.log('queryParams', searchParams);
      let queryResult = await queryList({ ...queryParams, ...searchParams });

      if (dataField.field === 'list') {
        tableData.value = queryResult.data;
      } else {
        tableData.value = queryResult.data[dataField.field];
        total.value = queryResult.data.total;
      }
    } catch (e) {
      console.log(e);
    } finally {
      tableLoading.value = false;
    }
    mergeToTree();
  }
  const treeList = ref([]);
  const mergeToTree = () => {
    treeList.value = [];
    console.log('formTypeList', formTypeList);
    let newTableData = tableData.value.map((item) => {
      item.formType = item.formType || item.classification;
      item.label = item.title;
      return item;
    });
    formTypeList.value.forEach((item) => {
      let newItem = JSON.parse(JSON.stringify(item));

      newItem.children = newTableData.filter((tableItem) => {
        return `${tableItem.formType}` === `${newItem.value}`;
      });

      treeList.value.push(newItem);
    });
    sortTreeByDate();
  };
  const sortTreeByDate = () => {
    treeList.value.forEach((item) => {
      item.children.sort((a, b) => {
        return new Date(b.createTime).getTime() - new Date(a.createTime).getTime();
      });
    });
  };

  return {
    queryData,
    tableLoading,
    treeList,
    tableData,
  };
};
